<template>
	<view class="content">
		<view class="user-from">
			<view class="from-item">
				<image src="../../../static/user/phone.png" mode="widthFix" />
				<input type="number" placeholder="请输入手机号" v-model="user.phone" placeholder-class="input" />
			</view>
			<view class="from-item-code">
				<view class="from-item">
					<image src="../../../static/user/code.png" mode="widthFix" />
					<input type="number" v-model="user.code" placeholder="请输入密码" placeholder-class="input" />
					<image src="../../../static/user/close.png" @click="handleClose" v-if="user.code.length > 0" mode="widthFix" class="close" />
				</view>
				<!--
				<view class="from-item btn" @click="handleCode">{{ code.text }}</view>
				-->
			</view>
			<view class="submit_btn" @click="handleSubmit">立即登录</view>
			<view class="protocol">
				<checkbox-group @change="checkChange"><checkbox value="1" color="#20C6BA" checked="true"/></checkbox-group>
				我已阅读并同意
				<navigator url="../../protocol/protocol?type=1" hover-class="none">《用户协议》</navigator>
				<navigator url="../../protocol/protocol?type=2" hover-class="none">《隐私协议》</navigator>
			</view>
		</view>
		<view class="wechat" @click="getWeChatCode" v-if="isWeixin">
			<image src="../../../static/user/wechat.png" mode="widthFix" />
			微信
		</view>
		<popup :close="isPopup">
			<view class="auth">
				<view class="close" @click="isPopup=false"><image src="../../../static/user/close.png" mode="widthFix" /></view>
				<view class="title">登录即享每天一课开心学习</view>
				<view class="phone">185 **** 44989</view>
				<view class="wechat_text">微信绑定号码登录</view>
				<view class="auth_btn" @click="handleWechat">一键登录</view>
				<view class="auth_phone" @click="isPopup=false">使用其他手机号</view>
				<view class="protocol">
					<checkbox-group @change="checkWechatChange"><checkbox value="1" color="#20C6BA" /></checkbox-group>
					我已阅读并同意
					<navigator url="../../protocol/protocol?type=1" hover-class="none">《明奥用户协议》</navigator>
					<navigator url="../../protocol/protocol?type=2" hover-class="none">《隐私协议》</navigator>
				</view>
			</view>
		</popup>
	</view>
</template>

<script>
import popup from '../../../components/popup/popup.vue';
import $util from '../../../utils/util.js'
export default {
	components: {
		popup
	},
	data() {
		return {
			user: {
				phone: '',
				code: ''
			},
			userChecked: true,
			weChecked: false,
			code: {
				isBool: false,
				text: '发送验证码',
				second: 60
			},
			isPopup:false,
			isWeixin: false
		};
	},
	
	onLoad() {
		this.isWeixin = this.isWechat()
		if(this.isWeixin){
			this.checkWeChatCode();//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
		}
	},
			
	mounted(){
		/* uni.navigateTo({
			url:"../../coach/search/search"
		}) */
		
		
	},
	methods: {
		/**
		 * 表单登录
		 */
		handleSubmit() {
			/* if (this.code.isBool == false) {
				this.$sys.showToast({
					title: '未发送验证码'
				});
				return;
			} */
			/* if (!this.$util.regularPhone(this.user.phone)) {
				this.$sys.showToast({
					title: '手机号输入不正确'
				});
				return;
			} */
			/* if (this.user.code == '') {
				this.$sys.showToast({
					title: '请输入验证码'
				});
				return;
			} */
			if (this.user.code == '') {
				this.$sys.showToast({
					title: '请输入密码'
				});
				return;
			}
			if (this.userChecked == false) {
				this.$sys.showToast({
					title: '未同意使用协议'
				});
				return;
			}
			/* this.$sys.showToast({
				title: '可登录'
			}); */
			
			let openid = uni.getStorageSync('openid')
			uni.request({
				url: this.websiteUrl + 'app/login', 
				data: {
					phone: this.user.phone,
					code: this.user.code,
					openid: openid
				},
				success: (res) => {
					
					if(res.data.code==0){
						//缓存用户ID
						uni.setStorageSync('userId', res.data.userId);
						//缓存token
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('userType', res.data.userType);
						uni.setStorageSync('businessId', res.data.businessId);
						//家长
						if(res.data.userType == 4){
							uni.setStorageSync('parent', res.data.parent);
							//跳转到首页
							uni.redirectTo({
								url: '/pages/index/index?bid='+res.data.businessId
							}) 
						}else{
							uni.setStorageSync('teacher', res.data.teacher);
							uni.redirectTo({
								url: '/pages/admin/sign_in/sign_in'
							}) 
						}
					}else if(res.data.code==500){
						uni.showToast({
							title: res.data.msg,
							duration: 5000
						});
					}else{
						uni.showToast({
							title: "后台服务不可用！",
							duration: 4000
						});
					}
				}
				
			}); 
		},
		
		
		/**
		 * 微信授权
		 */
		handleWechat(){
			if (this.weChecked == false) {
				this.$sys.showToast({
					title: '未同意使用协议'
				});
				return;
			}
			this.$sys.showToast({
				title: '功能开发中'
			});
		},
		/**
		 * 删除验证码
		 */
		handleClose() {
			this.user.code = '';
		},
		/**
		 * 发送验证码
		 */
		handleCode() {
			if (this.code.text != '发送验证码') {
				return;
			}
			if (!this.$util.regularPhone(this.user.phone)) {
				this.$sys.showToast({
					title: '手机号输入不正确'
				});
				return;
			}
			this.code.isBool = true;
			--this.code.second;
			this.code.text = this.code.second + 's';
			let setTime = setInterval(() => {
				if (this.code.second == 0) {
					this.code.text = '发送验证码';
					clearInterval(setTime);
				} else {
					this.code.text = '重新发送(' + this.code.second + 's)';
				}
				--this.code.second;
			}, 1000);
			
			//发送短信验证码
			uni.request({
				url: this.websiteUrl + 'app/getCheckCode', 
				data: {
					phone: this.user.phone
				},
				success: (res) => {
					if(res.data.code==0){
					}else if(res.data.code==500){
						uni.showToast({
							title: res.data.msg,
							duration: 2000
						});
					}else{
						uni.showToast({
							title: "后台服务不可用！",
							duration: 2000
						});
					}
				}
			}); 
			
		},
		/**
		 * 协议确认事件
		 * @param {Object} e
		 */
		checkChange(e) {
			this.userChecked = false;
			if (e.detail.value == '1') {
				this.userChecked = true;
			}
		},
		/**
		 * 微信授权协议
		 * @param {Object} e
		 */
		checkWechatChange(e) {
			this.weChecked = false;
			if (e.detail.value == '1') {
				this.weChecked = true;
			}
		},
		
		/*微信登录相关  start*/
		//方法：用来判断是否是微信内置的浏览器
		isWechat() {
			return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
		},
		//方法:用来提取code
		getUrlCode(name) {
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
							.replace(/\+/g, '%20')) || null
		},
					
		//检查浏览器地址栏中微信接口返回的code
		checkWeChatCode() {
			let code = this.getUrlCode('code')
			if (code) {
				this.getOpenidAndUserinfo(code)
			}else{
				//首次进入页面自动登陆
				if(this.isWeixin){
					this.getWeChatCode();
				}
			}
		},
					
		//请求微信接口，用来获取code
		getWeChatCode() {
			uni.request({
				url: this.websiteUrl + 'app/getBusinessInfo',
				data:{
					bid: this.$util.getUrlCode("bid")
				},
				success: (res) => {
					console.log(res)
					if (res.data.code == 0) {
						let business = res.data.business;
						let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
						let appid = business.appId; //'wxccb9cd1cd47fe641';  //微信appId
									
						//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
						window.location.href =
										"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
										appid + 
										"&redirect_uri=" +
										local +
										"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
					}
				}
			});
			
			
		},
					
		//把code传递给后台接口，静默登录
		getOpenidAndUserinfo(code) {
			uni.request({
				url: this.websiteUrl + 'app/getOpenidAndUserinfo?bid=' + this.$util.getUrlCode("bid"),
				data:{
					code: code
				},
				success: (res) => {
					console.log(res)
					if (res.data.code != 0) {
						uni.setStorageSync('openid', res.data.openid);
						/* uni.showToast({
							title: res.data.msg,
							duration: 3000,
							icon: 'none'
						}); */
						return
					}else{
						this.afterLogin(res)
					}
				}
			});
		},
					
		/*微信登录相关  end*/
		afterLogin(res){
			console.log(res)
			let user = res.data.user;
			let parentTeacherId = res.data.parentTeacherId;
			uni.setStorageSync('token', res.data.token);
			//缓存用户ID
			uni.setStorageSync('userId', res.data.userId);
			//缓存token
			uni.setStorageSync('token', res.data.token);
			uni.setStorageSync('userType', res.data.userType);
			uni.setStorageSync('businessId', res.data.businessId);
			let u = {
				avatar: user.avatar ? user.avatar : this.avatar,
				mobile: user.mobile,
				nickname: user.nickname ? user.nickname : '学员',
				parentId: parentTeacherId
			}
			uni.setStorage({
				key: 'u',
				data: u,
				success: () => {
					let userType = res.data.userType
					if(userType==4){
						uni.setStorageSync('parent', res.data.parent);
						uni.reLaunch({
							url: '/pages/index/index?bid='+this.$util.getUrlCode("bid")
						})
					}else{
						uni.setStorageSync('teacher', res.data.teacher);
						uni.reLaunch({
							url: '/pages/admin/sign_in/sign_in'
						})
					}
					
				}
			});
		}		
	}
};
</script>

<style lang="scss">
.user-from {
	@extend .global-padding;
	padding-top: 120rpx;
	.from-item {
		@extend .flex-space-between-center;
		height: 88rpx;
		line-height: 88rpx;
		background: #f8f9f9;
		border-radius: 44rpx;
		flex-wrap: nowrap;
		padding: 0px $base-interval;
		margin-bottom: 50rpx;
		position: relative;
		image {
			flex-shrink: 0;
			width: 22rpx;
		}
		input {
			width: 100%;
			flex-shrink: 1;

			padding-left: $base-interval;
		}
		.input {
			color: $text-color-nine;
			font-size: $font-size-base;
		}
		.close {
			width: 28rpx;
		}
	}
	.from-item-code {
		@extend .flex-space-between-center;
		flex-wrap: nowrap;
		.from-item {
			flex-shrink: 1;
			width: 100%;
		}
		.btn {
			margin-left: $base-interval;
			width: 180rpx;
			flex-shrink: 0;
			display: block;
			text-align: center;
			color: $text-color-nine;
		}
	}
	.submit_btn {
		@extend .global-button;
		margin-top: 2 * $lg-interval;
	}
	.protocol {
		checkbox {
			transform: scale(0.6);
		}
		@extend .flex-space-between-center;
		justify-content: center;
		font-size: $font-size-sm;
		margin-top: $lg-interval;
		color: $text-color-nine;
	}
}
.wechat {
	@extend .flex-space-between-center;
	color: $text-color-nine;
	position: fixed;
	bottom: 100rpx;
	width: 200rpx;
	justify-content: center;
	left: 50%;
	margin-left: -100rpx;
	padding: $base-interval 0px;
	image {
		width: 45rpx;
		margin-right: 10rpx;
	}
}
.auth {
	width: 80%;
	margin: auto;
	background: $bg-color-white;
	border-radius: $border-radius-base;
	text-align: center;
	.close{
		margin-left: 88%;
		display: inline-block;
		padding: $sm-interval;
		image{
			width:32rpx;
		}
	}
	.title{
		font-size: 36rpx;
		color: #263238;
		font-weight: 600;
	}
	.phone{
		font-size: 36rpx;
		color: #263238;
		font-weight: 600;
		margin-top:60rpx;
	}
	.wechat_text{
		color: $text-color-nine;
		font-size: $font-size-sm;
		margin-top:-10+$sm-interval;
	}
	.auth_btn{
		@extend .global-button;
		width: 80%;
		margin: auto;
		margin-top:50rpx;
	}
	.auth_phone{
		color: $text-color-six;
		margin-top:40rpx;
	}
	.protocol {
		padding-bottom: 60rpx;
		checkbox {
			transform: scale(0.6);
		}
		@extend .flex-space-between-center;
		justify-content: center;
		font-size: $font-size-sm;
		margin-top: $lg-interval;
		color: $text-color-nine;
	}
}
</style>
